const app = getApp();
const api = require("../../utils/api");

Component({
    properties: {
        navBarHeight: Number,
        shopId: Number
    },
    data: {
        isShow: false, //是否显示内容（防止出现空白）
        
        //购物车内容
        storeInfo: {
            id: '',
            code: '',
            name: '',
            address: ''
        },
        shopcartList: [],
        noContent: false,

        isAllSelected: true, //是否全选
        totalPrice: 0, //价格合计
        totalNumber: 0, //数量合计
    },
    methods: {
        initData() { //初始化数据
            this.getShopcartList();
        },
        
        getShopcartList() { //获取购物车列表
            api.post('/order/cart/list')
                .then(res => {
                    let list = [];
                    res.forEach(item => {
                        if(item.shopId == this.data.shopId) {
                            list = item.detailList;
                            this.setData({
                                isShow: true,
                                [`storeInfo.id`]: item.shopId,
                                [`storeInfo.code`]: item.shopNo,
                                [`storeInfo.name`]: item.shopName,
                                [`storeInfo.address`]: item.shopAddress,
                            })
                        }
                    });
                    list.forEach(item => {
                        item.selected = true;
                    });
                    this.setData({
                        shopcartList: list,
                        noContent: list.length == 0 ? true : false
                    });
    
                    this.dealSummary(1);
                })
        },
        dealSummary(type = 0) { //计算商品总数
            let sum = 0; //总件数
            let price = 0; //总价格
            let selectedNum = 0; //选中的数量
            
            let list = this.data.shopcartList;
            list.forEach(item => {
                if(item.selected) {
                    sum = sum + item.quantity;
                    price = price + parseFloat(item.price * item.quantity);
                    selectedNum++;
                }
            });
            this.setData({
                totalNumber: sum,
                totalPrice: price.toFixed(2),
                isAllSelected: selectedNum > 0 && selectedNum == this.data.shopcartList.length ? true : false
            });
            if(type == 0) {
                app.globalData.isRefreshStore = true;
            }
        },
    
        //操作数量
        quantityPlus(e) { //数量加
            let index = e.currentTarget.dataset.index;
            this.dealQuantity(index);
        },
        quantityMinus(e) { //数量减
            let index = e.currentTarget.dataset.index;
            let number = this.data.shopcartList[index].quantity;
            if(number == 1) { //数量为1，询问是否删除
                let item = this.data.shopcartList[index];
                wx.showModal({
                    title: '温馨提示',
                    content: `您是否确认删除商品【${item.productName}】？`,
                    success: res => {
                        if(res.confirm) {
                            this.deleteProduct(index);
                        }
                    }
                });
            } else {
                this.dealQuantity(index, -1);
            }
        },
        dealQuantity(index, quantity = 1) { //提交修改商品数量
            api.post(`/order/cart/quantity?id=${this.data.shopcartList[index].id}&diffQuantity=${quantity}`)
                .then(() => {
                    let number = this.data.shopcartList[index].quantity;
                    this.setData({
                        [`shopcartList[${index}].quantity`]: number + quantity, //修改数量
                    });
                    this.dealSummary(); //重新计算商品总数
                })
        },
        deleteProduct(index) { //删除商品(单个删除)
            let list = this.data.shopcartList;
            api.post(`/order/cart/remove?ids=${list[index].id}`)
                .then(() => {
                    list.splice(index, 1);
                    this.setData({
                        shopcartList: list
                    });
    
                    wx.showToast({
                        title: '删除成功',
                        icon: 'none'
                    });
                    this.dealSummary();
                })
        },
        deleteProductBySelected() { //批量所选商品(批量删除)
            wx.showModal({
                title: '温馨提示',
                content: `您是否确认删除所有已勾选的商品？`,
                success: res => {
                    if(res.confirm) {
                        let ids = [];
                        this.data.shopcartList.forEach(item => {
                            if(item.selected) {
                                ids.push(item.id)
                            }
                        });
                        api.post(`/order/cart/remove?ids=${ids.toString()}`)
                            .then(() => {
                                wx.showToast({
                                    title: '删除成功',
                                    icon: 'none'
                                });
                                this.setData({
                                    shopcartList: [],
                                    noContent: true
                                });
                                this.dealSummary();
                            })
                    }
                }
            });
        },
    
        //选择商品
        selectProduct(e) { //单选or取消单选商品
            let index = e.currentTarget.dataset.index;
            let choose = this.data.shopcartList[index].selected;
            this.setData({
                [`shopcartList[${index}].selected`]: !choose
            });
    
            this.dealSummary();
        },
        selectAll() { //点击全选
            let list = this.data.shopcartList;
            if(this.data.isAllSelected) { //原来是全选的情况
                list.forEach(item => {
                    item.selected = false;
                })
            } else {
                list.forEach(item => {
                    item.selected = true;
                })
            }
            this.setData({
                // isAllSelected: !this.data.isAllSelected,
                shopcartList: list
            });
            this.dealSummary();
        },
        
        gotoCheck() { //去结算shopcartCache
            if(this.data.totalNumber == 0) {
                wx.showToast({
                    title: '请选择要结算的商品!',
                    icon: 'none'
                });
                return;
            }

            if(app.globalData.userInfo.phone == '') {
                wx.showModal({
                    title: '温馨提示',
                    content: `请先完成会员注册！`,
                    success: res => {
                        if(res.confirm) {
                            wx.navigateTo({
                                url: '/pages/login/login?dir=1',
                            });
                        }
                    }
                });
                return;
            }

            //缓存选择要下单的商品
            let list = [];
            this.data.shopcartList.forEach(item => {
                if(item.selected) {
                    list.push(item);
                }
            })
            app.globalData.shopcartCacheList = list;

            wx.navigateTo({
                url: '/pages/orderConfirm/orderConfirm?shopId=' + this.data.shopId,
            });
        },
        viewAll() { //查看所有购物车
            wx.navigateTo({
                url: '/pages/shopcartAll/shopcartAll',
            })
        },
    }
})